package com.ruoyi.web.controller.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class Oss {
    private static final Logger LOG = LoggerFactory.getLogger(Oss.class);

    private static String ENDPOINT;

    private static String ACCESS_KEY_ID;

    private static String ACCESS_KEY_SECRET;

    // init static datas
    static {
        ENDPOINT = "oss-cn-shanghai.aliyuncs.com";
        ACCESS_KEY_ID = "LTAI4G8MZRVqtfRPAwjAu2Xa";
        ACCESS_KEY_SECRET = "y4GhaDgQr7rQ0aefg6XqDaiwsAtRiM";
    }

    private static final OSSClient getOSSClient() {
        return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }

    public static final boolean createBucket(String bucketName) {
        Bucket bucket = getOSSClient().createBucket(bucketName);
        return bucketName.equals(bucket.getName());
    }

    public static final void deleteBucket(String bucketName) {
        getOSSClient().deleteBucket(bucketName);
        LOG.info("删除" + bucketName + "Bucket成功");
    }

    public static final String uploadObject2OSS(File file, String bucketName, String diskName) {
        String resultStr = null;
        try {
            InputStream is = new FileInputStream(file);
            String fileName = file.getName();
            Long fileSize = file.length();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(fileName));

            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            // 上传文件
            PutObjectResult putResult = getOSSClient().putObject(bucketName, diskName + fileName, is, metadata);
            // 解析结果
            resultStr = putResult.getETag();
        } catch (Exception e) {
            LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return resultStr;
    }

    public static final String uploadObject2OSS2(MultipartFile file, String bucketName, String diskName,
                                                 String fileName) {
        String resultStr = null;
        try {
            InputStream is = file.getInputStream();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(fileName));
            // 上传文件
            PutObjectResult putResult = getOSSClient().putObject(bucketName, diskName + fileName, is, metadata);
            // 解析结果
            resultStr = putResult.getETag();
        } catch (Exception e) {
            LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return resultStr;
    }

    public static final String uploadString2OSS(String str, String fileName, String bucketName, String diskName) {
        String resultStr = null;
        try {
            byte[] content = str.getBytes();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(content.length);
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(fileName));
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + content.length + "Byte.");
            // 上传文件
            PutObjectResult putResult = getOSSClient().putObject(bucketName, diskName + fileName,
                    new ByteArrayInputStream(content), metadata);
            // 解析结果
            resultStr = putResult.getETag();
        } catch (Exception e) {
            LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return resultStr;
    }

    public static final String uploadObject2OSS(InputStream is, String fileName, Long fileSize, String bucketName,
                                                String diskName) {

        // 获取ossClient
        OSSClient ossClient = getOSSClient();

        try {

            // 生成OSS中Object的元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(is.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            metadata.setContentType(getContentType(fileName));
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");

            // 上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, diskName + fileName, is, metadata);

            // 解析结果
            return putResult.getETag();

        } catch (Exception e) {

            LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
            throw new RuntimeException("上传文件失败");

        } finally {
            ossClient.shutdown();
        }
    }

    public static final InputStream getOSS2InputStream(String bucketName, String diskName, String key) {
        OSSObject ossObj = getOSSClient().getObject(bucketName, diskName + key);
        return ossObj.getObjectContent();
    }

    public static void deleteFile(String bucketName, String diskName, String key) {
        getOSSClient().deleteObject(bucketName, diskName + key);
        LOG.info("删除" + bucketName + "下的文件" + diskName + key + "成功");
    }

    public static final String getContentType(String fileName) {
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);

        if ("bmp".equalsIgnoreCase(fileExtension))
            return "image/bmp";
        if ("gif".equalsIgnoreCase(fileExtension))
            return "image/gif";
        if ("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)
                || "png".equalsIgnoreCase(fileExtension))
            return "image/jpeg";
        if ("html".equalsIgnoreCase(fileExtension))
            return "text/html";
        if ("txt".equalsIgnoreCase(fileExtension))
            return "text/plain";
        if ("vsd".equalsIgnoreCase(fileExtension))
            return "application/vnd.visio";
        if ("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension))
            return "application/vnd.ms-powerpoint";
        if ("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension))
            return "application/msword";
        if ("xml".equalsIgnoreCase(fileExtension))
            return "text/xml";
        return "text/html";
    }
}
